package com.zeng.sys.authmd.restfulmodule.controller;

import com.zeng.nicecommon.util.ResponseUtil;
import com.zeng.nicecore.validation.ValidGroup;
import com.zeng.sys.authmd.apimodule.service.UserService;
import com.zeng.sys.authmd.apimodule.service.com.zeng.sys.authmd.apimodule.constant.PermissionType;
import com.zeng.sys.authmd.apimodule.vo.UserVo;
import com.zeng.sys.authmd.restfulmodule.util.Md5Util;
import com.zeng.sys.authmd.restfulmodule.util.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

@RequestMapping("sys")
@RestController
@Validated
public class SysController {
    private Logger logger = LoggerFactory.getLogger(SysController.class);
    @Autowired
    UserService userService;

    @Value("#{${sys.login.exp:20} * 60 * 1000}")
    Long exp;
    @Value("${sys.login.salt:zyl}")
    String salt;

    @RequestMapping("/login")
    public Object login(UserVo userVo,HttpServletRequest request) {
        logger.debug("用户[{}] 正在登陆", userVo.getUserAccount());

        UserVo oneByUserAccount = userService.getOneByUserAccount(userVo.getUserAccount());
        if (oneByUserAccount == null) {
            return ResponseUtil.badRequest("这个账号不存在");
        }
        userVo.setUserPw(userVo.getMd5Pw(salt));
        if (!oneByUserAccount.getUserPw().equals(userVo.getUserPw())) {
            return ResponseUtil.badRequest("密码错误");
        }
        TokenUtil tokenUtil = new TokenUtil();
        String token = Optional.ofNullable(request.getHeader("token")).orElse("");

        logger.debug("这个用户的登录携带token[{}]", token);
        if (TokenUtil.removeToken(token)) {
            logger.debug("已经删除 token [{}]", token);
        }


        token = tokenUtil.getToken(oneByUserAccount, exp + System.currentTimeMillis());
        TokenUtil.addLoginUser(oneByUserAccount.getCode(), oneByUserAccount);
        logger.debug("用户[{}] 登陆成功", userVo.getUserAccount());

        return ResponseUtil.success("登录成功").addData("token", token).addData("user", oneByUserAccount);


    }
    @RequestMapping("/logout")
    public Object logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        String codeInTokenCache = TokenUtil.getCodeInTokenCache(token);
        TokenUtil.removeLoginUser(codeInTokenCache);
        TokenUtil.removeToken(token);

        return ResponseUtil.success("退成登录,成功");

    }

    @RequestMapping("/register")
    public Object register(@Validated(ValidGroup.add.class) UserVo userVo) {

        UserVo oneByUserAccount = userService.getOneByUserAccount(userVo.getUserAccount());
        if (oneByUserAccount != null) {
            return ResponseUtil.badRequest("账号已被注册");
        }

        userVo.setUserPw(userVo.getMd5Pw(salt));
        UserVo addUser = userService.addOne(userVo);
        if (addUser == null) {
            return ResponseUtil.serviceError("请稍后重试");
        }
        return ResponseUtil.success("注册成功");

    }

    @RequestMapping("failReq")
    public Object failReq(HttpServletRequest request) {
        Object res = request.getAttribute("res");
        if (res instanceof ResponseUtil) {
            return res;
        }
        return ResponseUtil.serviceError("这个请求有问题");
    }

    @RequestMapping("refreshToken")
    public Object refreshToken(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return ResponseUtil.noAuthority("请重新登录");
        }
        TokenUtil tokenUtil = new TokenUtil();
        String userCode = TokenUtil.getCodeInTokenCache(token);
        TokenUtil.removeToken(token);
        UserVo loginUser = TokenUtil.getLoginUser(userCode);
        token = tokenUtil.getToken(loginUser, exp);
        return ResponseUtil.success("刷新token成功").addData("token", token);

    }

    @RequestMapping("test")
    public Object test(HttpServletRequest request) {
        UserVo userVo = userService.listUserApi("cdb6d3201caed0004e789b5252c9a5a1");
        System.out.println(userVo.getApis());
        if (userVo.getApis() != null) {
            return userVo.getApis();
        }
        String protocol = request.getProtocol();
        String remoteAddr = request.getRemoteAddr();
        String requestURI = request.getRequestURI();
        String remoteUser = request.getRemoteUser();
        int remotePort = request.getRemotePort();

        return ResponseUtil.success("操作成功")
                .addData("protocol", protocol)
                .addData("remoteAddr", remoteAddr)
                .addData("requestURI", requestURI)
                .addData("remoteUser", remoteUser)
                .addData("remotePort", remotePort)
                ;
    }

}
